package com.tanhua.backstage.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.backstage.vo.CommentBackstageVo;
import com.tanhua.backstage.vo.PageResult;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.HtMessageApi.MessageListApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MessageListService {
    @Reference(version = "1.0.0")
    private MessageListApi messageListApi;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private UserInfoMapper userInfoMapper;


    /**
     * 业务层实现功能:根据消息ID获取所有的评论列表信息
     *
     * @param page
     * @param pageSize
     * @param sortProp
     * @param sortOrder
     * @param messageId
     * @return
     */
    public PageResult getCommentLists(Integer page, Integer pageSize, String sortProp, String sortOrder, String messageId) {
        //创建PageResult对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //获取所有的评论信息
        PageInfo<Comment> pageInfo = messageListApi.getCommentLists(page, pageSize, sortProp, sortOrder, messageId);
        //创建返回的数据类型集合
        List<CommentBackstageVo> list = new ArrayList<>();
        //遍历评论列表,封装用户信息和评论信息
        for (Comment comment : pageInfo.getRecords()) {
            //创建CommentBackstageVo对象
            CommentBackstageVo backstageVo = new CommentBackstageVo();
            backstageVo.setId(comment.getId().toHexString());
            backstageVo.setContent(comment.getContent());
            backstageVo.setCreateDate(comment.getCreated());
            backstageVo.setUserId(comment.getUserId());
            //查找用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", comment.getUserId());
            backstageVo.setNickname(userInfoMapper.selectOne(wrapper).getNickName());
            list.add(backstageVo);
        }
        //总页数
        if (pageInfo.getTotal() % pageSize == 0) {
            pageResult.setPages(pageInfo.getTotal() / pageSize);
        } else {
            pageResult.setPages(pageInfo.getTotal() / pageSize + 1);
        }
        //封装总记录数
        pageResult.setCounts(pageInfo.getTotal());
        pageResult.setItems(list);
        //返回结果对象
        return pageResult;
    }
}
